package com.xxxx.yygh.hosp.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xxxx.yygh.common.result.Result;
import com.xxxx.yygh.hosp.listener.DictListener;
import com.xxxx.yygh.hosp.mapper.DictMapper;
import com.xxxx.yygh.hosp.service.DictService;
import com.xxxx.yygh.model.cmn.Dict;
import com.xxxx.yygh.vo.cmn.DictEeVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

    @Autowired
    private DictMapper dictMapper;

    // 根据数据id查询子数据列表
    @Override
    @Cacheable(value = "dict", keyGenerator = "keyGenerator")
    // ↑ 这个注解表示如果redis如果有缓存 则去查redis里的 如果没有/或者需要更新 则会查询后存进去
    public List<Dict> findChildData(Long id) {
        QueryWrapper<Dict> wrapper = new QueryWrapper();
        wrapper.eq("parent_id", id);
        List<Dict> dictList = dictMapper.selectList(wrapper);
        //向list集合每个dict对象中设置hasChildren
        for (Dict dict:dictList) {
            Long dictId = dict.getId();
            boolean isChild = isChildren(dictId);
            dict.setHasChildren(isChild);
        }
        return dictList;
    }

    // 导入数据词典
    @Override
    @CacheEvict(value = "dict", allEntries=true)
    // ↑ 这个注解表示如果有人导入了信息 则信息有变动 会删除相关缓存
    public void importDictData(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(),DictEeVo.class,new DictListener(dictMapper)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 导出数据字典
    @Override
    public void exportDictData(HttpServletResponse response) {
        // 设置下载信息
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = "dict";
        response.setHeader("Content-disposition", "attachment;filename="+ fileName + ".xlsx");
        // 查询数据库
        List<Dict> dictList = dictMapper.selectList(null);
        List<DictEeVo> eeVoList = new ArrayList<>();

        for (Dict dict : dictList) {
            DictEeVo dictEeVo = new DictEeVo();
            BeanUtils.copyProperties(dict, dictEeVo);
            eeVoList.add(dictEeVo);
        }

        // 调用方法写出去
        try {
            EasyExcel.write(response.getOutputStream(),DictEeVo.class).sheet("dict").doWrite(eeVoList);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 根据dictcode和value查询
    @Override
    public String getDictName(String dictCode, String value) {
        // 如果dictCode为空，直接根据value查询
        if (StringUtils.isEmpty(dictCode)) {
            // 根据value直接查询
            QueryWrapper<Dict> wrapper = new QueryWrapper<>();
            wrapper.eq("value", value);
            Dict dict = dictMapper.selectOne(wrapper);
            return dict.getName();
        } else {
            // 如果dictCode不为空 根据dictCode和value查询
            // 因为dictCode不是所有信息都有 父节点独有 所以先code查出id 再查出该id的子节点
            Dict codeDict = this.getDictByDictCode(dictCode);
            Long parentId = codeDict.getId();
            Dict finalDict = dictMapper.selectOne(new QueryWrapper<Dict>()
                    .eq("parent_id", parentId)
                    .eq("value", value));
            return finalDict.getName();
        }
    }

    @Override
    public List<Dict> findByDictCode(String dictCode) {
        Dict dict = this.getDictByDictCode(dictCode);
        List<Dict> childData = this.findChildData(dict.getId());
        return childData;
    }

    private Dict getDictByDictCode(String dictCode) {
        QueryWrapper<Dict> wrapper = new QueryWrapper();
        wrapper.eq("dict_code", dictCode);
        return dictMapper.selectOne(wrapper);
    }

    //判断id下面是否有子节点
    private boolean isChildren(Long id) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", id);
        Integer count = dictMapper.selectCount(wrapper);
        return count > 0;
    }
}
